package com.car.controller;

import com.car.mapper.UserMapper;
import com.car.pojo.*;
import com.car.pojo.LoginInfo;
import com.car.service.AdminService;
import com.car.service.EmpService;
import com.car.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * 登录Controller
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private EmpService empService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 管理员登录
     */
    @PostMapping("/admin/login")
    public Result adminLogin(@RequestBody Admin admin){
        log.info("管理员登录: {}", admin);
        LoginInfo info = adminService.login(admin);
        if (info != null){
            return Result.success(info);
        }
        return Result.error("用户名或密码错误");
    }

    /**
     * 员工登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        log.info("登录: {}", emp);
        LoginInfo info =  empService.login(emp);
        if (info != null){
            return Result.success(info);
        }
        return Result.error("用户名或密码错误");
    }

    /**
     * 用户登录
     */
    @PostMapping("/user/login")
    public Result userLogin(@RequestBody User user){
        log.info("用户登录: {}", user);
        LoginInfo info = userService.login(user);
        if (info != null){
            return Result.success(info);
        }
        return Result.error("用户名或密码错误");
    }

    @PostMapping("/user/register")
    public Result register(@RequestBody User user) {
        log.info("用户注册: {}", user);

        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsername(user.getUsername());
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }
        
        // 检查手机号是否已存在
        User existingPhone = userMapper.selectByPhone(user.getPhone());
        if (existingPhone != null) {
            return Result.error("手机号已经存在");
        }

        try {
            // 设置创建时间和更新时间
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());

            // 保存用户信息
            userService.save(user);
            return Result.success("注册成功");
        } catch (Exception e) {
            log.error("注册失败: {}", e.getMessage());
            return Result.error("注册失败，请稍后重试");
        }
    }


}
